@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>修改生产退料</title>
    <!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        .form-container {
            background: #fff;
            padding: 20px;
            margin: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #009688;
        }
        .warehouse-list li {
            padding: 8px 15px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
        }
        .warehouse-list li:hover {
            background-color: #f5f5f5;
        }
        .warehouse-list li.selected {
            background-color: #009688;
            color: white;
        }
        .btn-group {
            text-align: center;
            margin-top: 30px;
        }
        .btn-group .layui-btn {
            margin: 0 10px;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <div class="form-title">修改生产退料</div>
        
        <form class="layui-form" lay-filter="formDemo">
            <input type="hidden" id="recordId" name="id" value="">
            
            <div class="layui-form-item">
                <label class="layui-form-label">退料单编号</label>
                <div class="layui-input-block">
                    <input type="text" id="materialReturnNo" name="materialReturnNo" lay-verify="required" placeholder="请输入退料单编号" autocomplete="off" class="layui-input" readonly>
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">退料单名称</label>
                <div class="layui-input-block">
                    <input type="text" id="materialReturnName" name="materialReturnName" lay-verify="required" placeholder="请输入退料单名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">生产工单</label>
                <div class="layui-input-block">
                    <div class="layui-input-inline" style="width: 70%;">
                        <input type="text" id="productionOrder" name="productionOrder" lay-verify="required" placeholder="请输入生产工单" autocomplete="off" class="layui-input">
                    </div>
                    <div class="layui-input-inline">
                        <button type="button" class="layui-btn layui-btn-normal" id="searchOrderBtn">
                            <i class="layui-icon layui-icon-search"></i>
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">接收仓库</label>
                <div class="layui-input-block">
                    <div id="warehouseCascader" style="border: 1px solid #e6e6e6; padding: 10px; border-radius: 2px; cursor: pointer; background-color: white;">
                        <span id="warehouseDisplay" style="color: #999;">请选择</span>
                        <i class="layui-icon layui-icon-down" style="float: right; margin-top: 2px;"></i>
                    </div>
                    <input type="hidden" id="selectedWarehouse" name="warehouse" lay-verify="required">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">退料日期</label>
                <div class="layui-input-block">
                    <input type="text" id="returnDate" name="returnDate" lay-verify="required" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                </div>
            </div>
            
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea id="remarks" name="remarks" placeholder="请输入备注" class="layui-textarea"></textarea>
                </div>
            </div>
            
            <div class="btn-group">
                <button class="layui-btn" lay-submit lay-filter="formDemo">保存修改</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
            </div>
        </form>
    </div>

    <!-- 请勿在项目正式环境中引用该 layui.js 地址 -->
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        layui.use(['form', 'layer', 'laydate'], function(){
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            
            // 日期选择器
            laydate.render({
                elem: '#returnDate',
                type: 'date'
            });
            
            // 获取URL参数中的ID
            var urlParams = new URLSearchParams(window.location.search);
            var recordId = urlParams.get('id');
            
            if (recordId) {
                $('#recordId').val(recordId);
                loadData(recordId);
            } else {
                layer.msg('缺少记录ID参数', {icon: 2, time: 2000});
                setTimeout(function() {
                    // 返回到生产退料列表页面
                    window.location.href = '/ProductionMaterialReturn/GetProductMaterReturn?t=' + new Date().getTime();
                }, 2000);
            }
            
            // 加载数据
            function loadData(id) {
                var loadingIndex = layer.load(1, {
                    shade: [0.3, '#000']
                });
                
                $.ajax({
                    url: '/ProductionMaterialReturn/GetProductionMaterialReturnById',
                    type: 'GET',
                    data: { id: id },
                    success: function(res) {
                        layer.close(loadingIndex);
                        if (res.success) {
                            var data = res.data;
                            $('#materialReturnNo').val(data.returnOrderCode);
                            $('#materialReturnName').val(data.returnOrderName);
                            $('#productionOrder').val(data.productionWorkOrder);
                            $('#returnDate').val(data.returnDate.split('T')[0]); // 格式化日期
                            $('#remarks').val(data.remark);
                            
                            // 设置仓库信息
                            if (data.receiveWarehouse) {
                                parseAndSetWarehouse(data.receiveWarehouse);
                            }
                        } else {
                            layer.msg('加载数据失败: ' + res.message, {icon: 2, time: 3000});
                            setTimeout(function() {
                                // 返回到生产退料列表页面
                                window.location.href = '/ProductionMaterialReturn/GetProductMaterReturn?t=' + new Date().getTime();
                            }, 3000);
                        }
                    },
                    error: function() {
                        layer.close(loadingIndex);
                        layer.msg('请求失败', {icon: 2, time: 2000});
                        setTimeout(function() {
                            // 返回到生产退料列表页面
                            window.location.href = '/ProductionMaterialReturn/GetProductMaterReturn?t=' + new Date().getTime();
                        }, 2000);
                    }
                });
            }
            
            // 解析并设置仓库信息
            function parseAndSetWarehouse(warehouseValue) {
                // 这里可以根据实际情况解析仓库值并设置显示文本
                $('#selectedWarehouse').val(warehouseValue);
                $('#warehouseDisplay').text(warehouseValue).css('color', '#333');
            }
            
            // 仓库选择器
            $('#warehouseCascader').on('click', function() {
                openWarehouseDialog();
            });
            
            // 生产工单搜索
            $('#searchOrderBtn').on('click', function() {
                var productionOrder = $('#productionOrder').val().trim();
                if (!productionOrder) {
                    layer.msg('请先输入生产工单编号', {icon: 2, time: 2000});
                    return;
                }
                
                // TODO: 实现生产工单搜索功能
                layer.msg('生产工单搜索功能待实现', {icon: 1, time: 2000});
            });
            
            // 取消按钮
            $('#cancelBtn').on('click', function() {
                layer.confirm('确定要取消修改吗？', {icon: 3, title:'提示'}, function(index){
                    // 返回到生产退料列表页面
                    window.location.href = '/ProductionMaterialReturn/GetProductMaterReturn?t=' + new Date().getTime();
                    layer.close(index);
                });
            });
            
            // 表单提交
            form.on('submit(formDemo)', function(data){
                console.log(data.field);
                
                // 验证必填字段
                if (!data.field.materialReturnName) {
                    layer.msg('请输入退料单名称', {icon: 2, time: 2000});
                    return false;
                }
                if (!data.field.productionOrder) {
                    layer.msg('请选择生产工单', {icon: 2, time: 2000});
                    return false;
                }
                if (!data.field.warehouse) {
                    layer.msg('请选择接收仓库', {icon: 2, time: 2000});
                    return false;
                }
                if (!data.field.returnDate) {
                    layer.msg('请选择退料日期', {icon: 2, time: 2000});
                    return false;
                }
                
                // 添加调试信息 - 查看表单数据
                console.log('表单原始数据:', data.field);
                
                // 构建更新数据
                var updateData = {
                    id: parseInt(data.field.id),
                    returnOrderCode: data.field.materialReturnNo,
                    returnOrderName: data.field.materialReturnName,
                    productionWorkOrder: data.field.productionOrder,
                    receiveWarehouse: data.field.warehouse,
                    returnDate: data.field.returnDate + 'T00:00:00.000Z',
                    remark: data.field.remarks || ''
                };
                
                // 添加调试信息
                console.log('发送的更新数据:', updateData);
                
                // 显示保存中状态
                var loadingIndex = layer.load(1, {
                    shade: [0.3, '#000']
                });
                
                // 确保发送的是转换后的数据
                console.log('准备发送的JSON:', JSON.stringify(updateData));
                
                // 先测试数据接收
                $.ajax({
                    url: '/ProductionMaterialReturn/TestDataReceive',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(updateData),
                    success: function(testRes) {
                        console.log('数据接收测试结果:', testRes);
                        
                        if (!testRes.success) {
                            layer.close(loadingIndex);
                            layer.msg('数据格式错误: ' + testRes.message, {icon: 2, time: 3000});
                            return;
                        }
                        
                        // 数据格式正确，进行实际更新
                        $.ajax({
                            url: '/ProductionMaterialReturn/UpdateProductionMaterialReturn',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(updateData),
                            success: function(res) {
                                layer.close(loadingIndex);
                                console.log('更新结果:', res);
                                if (res.success) {
                                    layer.msg('修改成功', {icon: 1, time: 2000});
                                    setTimeout(function() {
                                        // 返回到生产退料列表页面并刷新（添加时间戳强制刷新）
                                        window.location.href = '/ProductionMaterialReturn/GetProductMaterReturn?t=' + new Date().getTime();
                                    }, 2000);
                                } else {
                                    layer.msg('修改失败: ' + res.message, {icon: 2, time: 5000});
                                }
                            },
                            error: function(xhr, status, error) {
                                layer.close(loadingIndex);
                                console.error('更新请求失败:', xhr, status, error);
                                layer.msg('更新请求失败: ' + error, {icon: 2, time: 3000});
                            }
                        });
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadingIndex);
                        console.error('测试请求失败:', xhr, status, error);
                        layer.msg('测试请求失败: ' + error, {icon: 2, time: 3000});
                    }
                });
                
                return false;
            });
            
            // 仓库选择对话框
            function openWarehouseDialog() {
                var selectedPath = [];
                
                layer.open({
                    type: 1,
                    title: '选择仓库',
                    area: ['600px', '400px'],
                    content: buildWarehouseDialogContent(),
                    btn: ['确定', '取消'],
                    btn1: function(index) {
                        if (selectedPath.length === 0) {
                            layer.msg('请选择仓库', { icon: 2, time: 2000 });
                            return false;
                        }
                        
                        // 构建显示文本和值
                        var displayText = selectedPath.map(item => item.name).join(' > ');
                        var value = selectedPath[selectedPath.length - 1].id;
                        
                        // 设置选中值
                        $('#warehouseDisplay').text(displayText).css('color', '#333');
                        $('#selectedWarehouse').val(value);
                        
                        layer.close(index);
                        layer.msg('仓库选择成功', { icon: 1, time: 1500 });
                    },
                    success: function() {
                        initWarehouseDialog();
                    }
                });
                
                function buildWarehouseDialogContent() {
                    return `
                        <div style="padding: 20px;">
                            <div style="display: flex; height: 300px;">
                                <div style="width: 180px; border: 1px solid #e6e6e6; margin-right: 10px;">
                                    <div style="background: #f5f5f5; padding: 8px; border-bottom: 1px solid #e6e6e6; font-weight: bold;">一级仓库</div>
                                    <ul id="level1" class="warehouse-list" style="margin: 0; padding: 0; list-style: none; max-height: 260px; overflow-y: auto;">
                                        <!-- 一级仓库列表 -->
                                    </ul>
                                </div>
                                <div style="width: 180px; border: 1px solid #e6e6e6; margin-right: 10px;">
                                    <div style="background: #f5f5f5; padding: 8px; border-bottom: 1px solid #e6e6e6; font-weight: bold;">二级仓库</div>
                                    <ul id="level2" class="warehouse-list" style="margin: 0; padding: 0; list-style: none; max-height: 260px; overflow-y: auto;">
                                        <!-- 二级仓库列表 -->
                                    </ul>
                                </div>
                                <div style="width: 180px; border: 1px solid #e6e6e6;">
                                    <div style="background: #f5f5f5; padding: 8px; border-bottom: 1px solid #e6e6e6; font-weight: bold;">三级仓库</div>
                                    <ul id="level3" class="warehouse-list" style="margin: 0; padding: 0; list-style: none; max-height: 260px; overflow-y: auto;">
                                        <!-- 三级仓库列表 -->
                                    </ul>
                                </div>
                            </div>
                        </div>
                    `;
                }
                
                function initWarehouseDialog() {
                    // 模拟仓库数据
                    var warehouseData = {
                        "预置仓库": {
                            "1号仓1区": ["1号仓1区1位", "1号仓1区2位", "1号仓1区3位"],
                            "1号仓2区": ["1号仓2区1位", "1号仓2区2位"],
                            "2号仓1区": ["2号仓1区1位", "2号仓1区2位"]
                        },
                        "测试仓库": {
                            "1号仓1区": ["1号仓1区1位", "1号仓1区2位"],
                            "2号仓1区": ["2号仓1区1位"]
                        },
                        "云中港项目": {
                            "1号仓1区": ["1号仓1区1位", "1号仓1区2位", "1号仓1区3位"]
                        }
                    };
                    
                    // 初始化一级仓库
                    var level1Html = '';
                    Object.keys(warehouseData).forEach(function(warehouse) {
                        level1Html += '<li data-id="' + getWarehouseCode(warehouse) + '" data-name="' + warehouse + '">' + warehouse + '</li>';
                    });
                    $('#level1').html(level1Html);
                    
                    // 绑定一级仓库点击事件
                    $('#level1').on('click', 'li', function() {
                        $('#level1 li').removeClass('selected');
                        $(this).addClass('selected');
                        
                        selectedPath = [{
                            id: $(this).data('id'),
                            name: $(this).data('name')
                        }];
                        
                        var warehouseName = $(this).data('name');
                        var areas = warehouseData[warehouseName];
                        
                        var level2Html = '';
                        Object.keys(areas).forEach(function(area) {
                            var areaId = selectedPath[0].id + '_' + getAreaCode(area);
                            level2Html += '<li data-id="' + areaId + '" data-name="' + area + '">' + area + '</li>';
                        });
                        $('#level2').html(level2Html);
                        $('#level3').html('');
                    });
                    
                    // 绑定二级仓库点击事件
                    $('#level2').on('click', 'li', function() {
                        $('#level2 li').removeClass('selected');
                        $(this).addClass('selected');
                        
                        selectedPath = selectedPath.slice(0, 1);
                        selectedPath.push({
                            id: $(this).data('id'),
                            name: $(this).data('name')
                        });
                        
                        var warehouseName = selectedPath[0].name;
                        var areaName = $(this).data('name');
                        var locations = warehouseData[warehouseName][areaName];
                        
                        var level3Html = '';
                        locations.forEach(function(location) {
                            var locationId = selectedPath[1].id + '_' + getLocationCode(location);
                            level3Html += '<li data-id="' + locationId + '" data-name="' + location + '">' + location + '</li>';
                        });
                        $('#level3').html(level3Html);
                    });
                    
                    // 绑定三级仓库点击事件
                    $('#level3').on('click', 'li', function() {
                        $('#level3 li').removeClass('selected');
                        $(this).addClass('selected');
                        
                        selectedPath = selectedPath.slice(0, 2);
                        selectedPath.push({
                            id: $(this).data('id'),
                            name: $(this).data('name')
                        });
                    });
                }
                
                // 获取仓库代码
                function getWarehouseCode(warehouseName) {
                    var codeMap = {
                        "预置仓库": "yz",
                        "测试仓库": "cz", 
                        "云中港项目": "yg"
                    };
                    return codeMap[warehouseName] || "unknown";
                }
                
                function getAreaCode(areaName) {
                    if (areaName.includes("1号仓1区")) return "1";
                    if (areaName.includes("1号仓2区")) return "2";
                    if (areaName.includes("2号仓1区")) return "3";
                    return "1";
                }
                
                function getLocationCode(locationName) {
                    if (locationName.includes("1位")) return "1";
                    if (locationName.includes("2位")) return "2";
                    if (locationName.includes("3位")) return "3";
                    return "1";
                }
            }
        });
    </script>
</body>
</html> 